//
//  Project_Step8ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/25.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Project_Step8ViewController.h"
#import "Project_Step7ViewController.h"
#import "Project_TabViewController.h"
#import "BottomActionView.h"
#import "ProjectManager.h"
#import <MBProgressHUD.h>
#import <PopMenu.h>
#import "ProvinceData.h"
#import "ProjectContentViewController.h"
#import "CustomActivity.h"


@interface Project_Step8ViewController (){
    MBProgressHUD *HUD;
}

@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong) BottomActionView *footerView;
@property (nonatomic,strong) PopMenu *popMenu;
@property (nonatomic,strong) NSString *cityName;

@end

@implementation Project_Step8ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
    self.cityName = nil;
    [self generateReport];
    //[self loadWebData];
    // Do any additional setup after loading the view.
}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"汇总";
    
    UIView *actionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, kNavigation_Bar_Height)];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setTitle:@"分享" forState:UIControlStateNormal];
    [shareBtn setTintColor:[UIColor whiteColor]];
    shareBtn.titleLabel.font = [UIFont systemFontOfSize: kListTitleFontSize];
    shareBtn.frame = CGRectMake(0, 0, [Tools sizeOfSingleLineText:@"分享" withSize:kListTitleFontSize].width + 5, [Tools sizeOfSingleLineText:@"分享" withSize:kListTitleFontSize].height + 5);
    [shareBtn addTarget:self action:@selector(shareButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [actionView addSubview:shareBtn];
    shareBtn.centerY = kNavigation_Bar_Height/2;
//    shareBtn.hidden = YES;
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [closeBtn setTintColor:[UIColor whiteColor]];
    closeBtn.titleLabel.font = [UIFont systemFontOfSize: kListTitleFontSize];
    closeBtn.frame = CGRectMake(CGRectGetMaxX(shareBtn.frame) + 5, 0, [Tools sizeOfSingleLineText:@"分享" withSize:kListTitleFontSize].width + 5, [Tools sizeOfSingleLineText:@"分享" withSize:kListTitleFontSize].height + 5);
    [closeBtn addTarget:self action:@selector(onBackToProject) forControlEvents:UIControlEventTouchUpInside];
    [actionView addSubview:closeBtn];
    closeBtn.centerY = kNavigation_Bar_Height/2;
    
    actionView.width = CGRectGetMaxX(closeBtn.frame);
    
    
    
    
//    NSArray *imageList = @[[UIImage imageNamed:@"menuChat.png"], [UIImage imageNamed:@"menuUsers.png"],[UIImage imageNamed:@"menuClose.png"]];
//    sideBar = [[CDSideBarController alloc] initWithImages:imageList];
//    sideBar.delegate = self;
//    [sideBar insertMenuButtonOnView:actionView atPosition:CGPointMake(0, 0)];
    
    //自定义按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithCustomView:actionView];
    self.navigationItem.rightBarButtonItem = backBtn;
    
    //列表
    self.webView = [[UIWebView alloc] initWithFrame:kScreen_Bounds];
//    self.webView.height -= kStatus_Navigation_Height;
    if (iPhone_X) {
        self.webView.height -= KIphoneX_Adjust_Height;
    }
    self.webView.delegate = self;
    
    self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    self.webView.scalesPageToFit = YES;
    self.webView.multipleTouchEnabled = YES;
    self.webView.userInteractionEnabled = YES;
    [self.view addSubview: self.webView];
}

- (void) generateReport {
    if (![Tools isEmpty:self.report]) {
        NSURLRequest *request =[NSURLRequest requestWithURL:[Tools getResourceFullPathURL:self.report]];
        [MBProgressHUD showMessage:@"项目报告获取中..." toView:self.view];
        [self.webView loadRequest:request];
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.project_id forKey:@"project_id"];
    [params setValue:self.userName forKey:@"user_name"];
    
    [MBProgressHUD showMessage:@"项目报告生成中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_REPORT token:[AccountManager manager].token paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        self.report = obj.report;
        NSURLRequest *request =[NSURLRequest requestWithURL:[Tools getResourceFullPathURL:obj.report]];
        [MBProgressHUD showMessage:@"项目报告获取中..." toView:self.view];
        [self.webView loadRequest:request];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"生成失败！"];
    }];
}


- (void)shareButtonClicked {
    NSString *shareText = @"中广欧特斯5C舒适家";
    UIImage *shareImage = [UIImage imageNamed:@"share_icon"];
    NSURL *shareUrl = [Tools getResourceFullPathURL:self.report];
    NSArray *activityItemsArray = @[shareText,shareImage,shareUrl];
    
    // 自定义的CustomActivity，继承自UIActivity
    CustomActivity *customActivity = [[CustomActivity alloc]initWithTitle:shareText ActivityImage:[UIImage imageNamed:@"share_icon"] URL:shareUrl ActivityType:@"Custom"];
//    CustomActivity *customActivity = [[CustomActivity alloc]initWithTitle: shareText ActivityImage:[UIImage imageNamed:@"custom.png"] URL: shareUrl ActivityType:@"Custom" ShareContext:activityItemsArray];
    NSArray *activityArray = @[customActivity];
    
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItemsArray applicationActivities:activityArray];
    activityVC.modalInPopover = YES;
    
    UIActivityViewControllerCompletionWithItemsHandler itemsBlock = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
        NSLog(@"activityType == %@",activityType);
        if (completed == YES) {
            NSLog(@"completed");
        }else{
            NSLog(@"cancel");
        }
    };
    activityVC.completionWithItemsHandler = itemsBlock;
    
    [self presentViewController:activityVC animated:YES completion:nil];
}
/**
 *  直接跳转到项目页面
 */
-(void)onBackToProject {
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:nil
//                                      shareText:@"你要分享的文字"
//                                     shareImage:[UIImage imageNamed:@"icon.png"]
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ,UMShareToRenren,UMShareToDouban,UMShareToEmail,UMShareToSms,UMShareToFacebook,UMShareToTwitter,nil]
//                                       delegate:nil];
//    UMShareToSina、UMShareToTencent、UMShareToWechatSession、UMShareToWechatTimeline、UMShareToQzone、UMShareToQQ、UMShareToRenren、UMShareToDouban、UMShareToEmail、UMShareToSms、UMShareToFacebook、UMShareToTwitter
    
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [(Project_TabViewController*)tmp refreshData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}



- (void)webViewDidStartLoad:(UIWebView *)webView {
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [MBProgressHUD hideHUDForView:self.view];
//    CGSize contentSize = webView.scrollView.contentSize;
//    CGSize viewSize = self.view.bounds.size;
//
//    float rw = viewSize.width / 250;
//
//    webView.scrollView.minimumZoomScale = rw;
//    webView.scrollView.maximumZoomScale = rw;
//    webView.scrollView.zoomScale = rw;
    
//    NSString *javascript = [NSString stringWithFormat:@"var viewPortTag=document.createElement('meta');  \
//                            viewPortTag.id='viewport';  \
//                            viewPortTag.name = 'viewport';  \
//                            viewPortTag.content = 'width=%d; initial-scale=0.58; maximum-scale=2.0; user-scalable=0;';  \
//                            document.getElementsByTagName('head')[0].appendChild(viewPortTag);" , (int)webView.bounds.size.width];
//
//    [webView stringByEvaluatingJavaScriptFromString:javascript];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getCityByGUID:(NSString*)guidId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:guidId forKey:@"cid"];
    [HttpClient getWithUrl:HTTP_GET_CITY paramDic:param resultClass:[ProvinceData class] success:^(ProvinceData *obj) {
        self.cityName = obj.getCityByIdResult.name;
    } failure:^(NSError *error) {
        CMLog(@"错误信息为：%@",error);
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
